from flask import Flask, make_response, request, session, render_template, url_for, Response, send_from_directory

import json

import string

import hashlib

import random

import time

import urllib

import redis

r = redis.Redis(host="127.0.0.1", port=6379)

app = Flask(__name__)


#公众号appid ，非测试使用，记得获取jsapi_ticket时一定要添加ip白名单，否则获取不到值

appid = 'wxd3ee0ceae85cdb76'

sceret = '41b9f5dbd4bb3283a71cd5ef2cb9c729'

#JS接口安全域名
#22210qg528.imwork.net/jssdk,主要是为了和路由@app.route('/MP_verify_PG8NVuoJl5WTt606.txt')相对应

class Sign:
    def __init__(self, jsapi_ticket, url):
        self.ret = {
            'nonceStr': self.__create_nonce_str(),
            'jsapi_ticket': jsapi_ticket,
            'timestamp': self.__create_timestamp(),
            'url': url,
        }
    # 生成随机字符串nodeceStr
    def __create_nonce_str(self):
        nonceStr = ''.join(
            random.choice(string.ascii_letters + string.digits)
            for _ in range(15))
        print("nonceStr:" + nonceStr)
        return nonceStr  #创建随机字符串
    # 生成时间戳
    def __create_timestamp(self):
        timeSTAMP = int(time.time())
        print("timestamp:" + str(timeSTAMP))
        return timeSTAMP  # 创建一个时间戳
    def sign(self):
        string = '&'.join([
            '%s=%s' % (key.lower(), self.ret[key]) for key in sorted(self.ret)
        ])  # 根据字符的ASCII值进行排序，拼接
        print("string:" + string)
        self.ret['signature'] = hashlib.sha1(
            string.encode('utf-8')).hexdigest()  # 对字符串进行sha1加密
        return self.ret
# 获取access_token
def get__token():
    #从redis中获取到的值为字节类型，需要转化为字符串类型str(ACCESS_TOKEN,encoding='utf-8')
    ACCESS_TOKEN = r.get("wx:ACCESS_TOKEN")
    if ACCESS_TOKEN is not None:
        return str(ACCESS_TOKEN, encoding='utf-8')
    else:
        try:
            token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}".format(
                appid, sceret)  # 创建获取token的url
            response = urllib.request.urlopen(token_url)
            b = response.read().decode('utf-8')
            token = json.loads(b)

            ACCESS_TOKEN = token.get("access_token")

            r.set(
                'wx:ACCESS_TOKEN',
                ACCESS_TOKEN,
                ex=7200,
            )  # 将获取到的 ACCESS_TOKEN 存入redis中并且设置过期时间为7200s

            return ACCESS_TOKEN
        except Exception as e:
            return e
#获取jsapi_ticket
def get_jsapi_ticket():
    #从redis中获取到的值为字节类型，需要转化为字符串类型str(ticket,encoding='utf-8')
    ticket = r.get("wx:ticket")
    if ticket is not None:
        tic = str(ticket, encoding='utf-8')
        return format(tic)
    else:
        try:
            token = get__token()
            ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={}&type=jsapi".format(
                token)

            get_ticket = urllib.request.urlopen(ticket_url)

            c = get_ticket.read().decode("utf-8")

            js_ticket = json.loads(c)

            ticket = js_ticket.get("ticket")

            r.set("wx:ticket", str(ticket), ex=7200)
            #r.setex('jsapi_ticket', ticket, 7200)
            print("获取到")
            return ticket
        except Exception as e:
            return e
#flask请求路由方法
#需要使用jssdk的页面
@app.route('/jssdk', methods=['GET'])
def jssdk_config():
    #url = request.data.get("url")
    #print(url)
    #url="22210qg528.imwork.net/jssdk"
    url = request.url

    ticket = get_jsapi_ticket()

    sign = Sign(ticket, url)

    results = {"appid": appid, "result": sign.sign()}
    response_heade = {'Access-Control-Allow-Origin': '*'}

    result = results["result"]

    print("signature:" + result["signature"])

    return render_template("index.html",
                           timestamp=result["timestamp"],
                           nonceStr=result["nonceStr"],
                           signature=result["signature"])
#在Js接口安全域名出添加，微信服务器会发送一个请求，将这个请求定位到这个目录下
@app.route('/jssdk/MP_verify_AqHoQvkFSx2VSAHB.txt')
def get_mp_verify():
    return send_from_directory(app.static_folder,
                               "MP_verify_AqHoQvkFSx2VSAHB.txt")


if __name__ == '__main__':
    app.run(host="127.0.0.1", port=80, debug=True)
